package com.Pan.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * @Description: Json转换工具类
 * @Author: zhangjie
 * @Date: 10/9/18 PM7:56
 */
public class JsonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {

        // 未找到字段不报错
        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 空属性对象
        MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        // null不进行序列化
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        //Jackson将对象转换为json字符串时，设置默认的时间格式
        DateFormat dateformat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MAPPER.setDateFormat(dateformat);

        // 防止Double类型序列号后显示科学记数法，保留4位小数
        SimpleModule module = new SimpleModule();
        module.addSerializer(Double.class, new StdSerializer(BigDecimal.class) {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                BigDecimal bigDecimal = new BigDecimal(o.toString());
                bigDecimal = bigDecimal.setScale(4, BigDecimal.ROUND_UP);
                jsonGenerator.writeNumber(bigDecimal);
            }
        });
        MAPPER.registerModule(module);

        // 将null的属性转换为空串
//        MAPPER.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
//            @Override
//            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
//                jsonGenerator.writeString("");
//            }
//        });

    }
    public static ObjectMapper getObjectMapper(){
        return MAPPER;
    }
    /**
     * 对象转json
     *
     * @param obj 要转换的对象
     * @date  11/9/18 AM11:57
     * @return String
     */
    public static String toJsonString(Object obj) {
        if (obj == null){
            return null;
        }
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("JSON 序列化错误", e);
        }
        return null;
    }

    /**
     * 对象转json
     *
     * @param jsonData json数据
     * @param beanType 转换对象类型
     * @date  11/9/18 AM11:57
     * @return T
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        if (Strings.isNullOrEmpty(jsonData)){
            return null;
        }
        try {
            return MAPPER.readValue(jsonData, beanType);
        } catch (Exception e) {
            logger.error("JSON 反序列化错误", e);
        }

        return null;
    }
    /**
     * 对象转json
     *
     * @param jsonData json数据
     * @param typeReference 转换对象类型
     * @date  11/9/18 AM11:57
     * @return T
     */
    public static <T> T parseObject(String jsonData, TypeReference<T> typeReference) {
        if (Strings.isNullOrEmpty(jsonData)){
            return null;
        }
        try {
            return MAPPER.readValue(jsonData, typeReference);
        } catch (Exception e) {
            logger.error("JSON 反序列化错误", e);
        }
        return null;
    }

}
